//
//  PictureSelectorViewController.swift
//  SinaWeibo
//
//  Created by 李旭阳 on 15/11/19.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let column: CGFloat = 4
private let pictureCellMaigin: CGFloat = 10
private let maxImageCount = 3

class PictureSelectorViewController: UICollectionViewController {
    
    //增加图片数组属性
    lazy var imageList = [UIImage]()
    
    //MARK: 构造方法
    init(){
        let layout = UICollectionViewFlowLayout()
        //设置layout
        let w = (screenW - (column + 1) * pictureCellMaigin) / column
        layout.itemSize = CGSize(width: w, height: w)
        layout.sectionInset = UIEdgeInsets(top: pictureCellMaigin, left: pictureCellMaigin, bottom: pictureCellMaigin, right: pictureCellMaigin)
        super.init(collectionViewLayout: layout)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = (imageList.count == maxImageCount) ? 0 : 1
        return imageList.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        //绑定数据源
        if indexPath.item == imageList.count {
            cell.image = nil
        } else {
            cell.image = imageList[indexPath.item]
        }
        cell.selectorCellDelegate = self
        return cell
    }
}

//代理方法
extension PictureSelectorViewController: PictureSelectorCellDelegate {
    func userWillAddPicture(cell: PictureSelectorCell){
        print("添加图片")
        //使用系统的图片选择器
        let picker = UIImagePickerController()
        picker.delegate = self
        //设置是否允许编辑  在上传头像的时候 需要打开
        //picker.allowsEditing = true
        presentViewController(picker, animated: true, completion: nil)
    }
    func userWillDeletePicture(cell: PictureSelectorCell){
        let indexPath = collectionView?.indexPathForCell(cell)
        self.imageList.removeAtIndex(indexPath!.item)
        //刷新视图
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            cell.alpha = 0
            }) { (_) -> Void in
                cell.alpha = 1
                self.collectionView?.reloadData()
        }
        print("删除图片")
    }
}

//遵守图片选择器的协议
extension PictureSelectorViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //添加图片
        imageList.append(image)
        //刷新集合视图
        collectionView?.reloadData()
        
        //一旦实现了协议方法 dismiss 就交给程序员
        dismissViewControllerAnimated(true, completion: nil)
    }
}

//定义协议
@objc protocol PictureSelectorCellDelegate: NSObjectProtocol {
    //添加图片的方法
    optional func userWillAddPicture(cell: PictureSelectorCell)
    //删除图片的方法
    optional func userWillDeletePicture(cell: PictureSelectorCell)
}

//自定义cell
class PictureSelectorCell: UICollectionViewCell {
    
    //定义代理
    weak var selectorCellDelegate: PictureSelectorCellDelegate?
    @objc private func addBtnDidClick(){
        selectorCellDelegate?.userWillAddPicture?(self)
    }
    @objc private func deleteBtnDidClick(){
        selectorCellDelegate?.userWillDeletePicture?(self)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:  定义图片数据模型 赋值
    var image: UIImage? {
        didSet{
            deleteBtn.hidden = (image == nil)
            if image != nil{
                addBtn.setBackgroundImage(image, forState: .Normal)
            } else {
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }
        }
    }
    //MARK: 设置UI 控件
    private func setupUI(){
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            //edges 相对于 contentView 四周约束边距为0
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
        }
        
        //添加事件
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        
    }
    
    
    //MARK: 懒加载
    private lazy var addBtn: UIButton = UIButton(title: nil, backImage: "compose_pic_add", color: nil)
    private lazy var deleteBtn: UIButton = UIButton(title: nil, backImage: "compose_photo_close", color: nil)
}